package com.esun.rabbit2.viewer.mainact.optionact;

import java.util.Calendar;

import org.androidpn.client.Constants;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.esun.config.Config;
import com.esun.rabbit2.communicaters.option.SendPushInfoCommunicater;
import com.esun.ui.R;
import com.esun.util.log.EDebug;

/**
 * @Title: PushAct.java
 * @Package com.esun.rabbit2.viewer.mainact.optionact
 * @Description: 设置推送详情
 * @author 孔祥攀
 * @date 2012-7-9 上午10:36:57 copy right 深圳市易讯天空网络技术有限公司
 */
public class PushAct extends Activity implements OnClickListener, OnCheckedChangeListener {

	/** 返回按钮 */
	private ImageButton btnBack;

	/** 保存按钮 */
	private Button btnSave;

	/** 总开关 */
	private CheckBox cbxMasterPushSwitch;

	/** 提醒时间开关 */
	private CheckBox cbxTimePushSiwtch;

	/** 双色球 */
	private CheckBox cbxLotteryPushSwitch_SSQ;

	/** 大乐透 */
	private CheckBox cbxLotteryPushSwitch_DLT;

	/** 任9 */
	private CheckBox cbxLotteryPushSwitch_RXJ;

	/** 福彩3D */
	private CheckBox cbxLotteryPushSwitch_FC3D;

	/** 提醒双色球时间开关 */
	private CheckBox cbxTimePushSwitch_SSQ;

	/** 提醒大乐透时间开关 */
	private CheckBox cbxTimePushSwitch_DLT;

	/** 提醒任9时间开关 */
	private CheckBox cbxTimePushSwitch_RXJ;

	/** 提醒福彩3D时间开关 */
	private CheckBox cbxTimePushSwitch_FC3D;

	/**
	 * @Fields linearAllPushContent : 承载所有push开关内容的控件
	 */
	private LinearLayout linearAllPushContent;

	/**
	 * @Fields linearTimePushContent : 承载购彩时间提醒的控件
	 */
	private LinearLayout linearTimePushContent;

	/**
	 * @Fields linearSetTime : 设置提醒时间的控件
	 */
	private LinearLayout linearSetTime;

	/** @Fields tvSetTime : 显示提醒时间textview */
	private TextView tvSetTime;

	/** 推送总开关 */
	private boolean state_masterPushSwitch = true;

	/** 设置时间hours */
	private String remindTime_hours = Config.NUM00;

	/** 设置时间min */
	private String remindTime_mins = Config.NUM00;

	/** 时间推送开关 */
	private boolean state_timePushSwitch = false;

	/** 双色球开奖推送开关状态 */
	private boolean state_SSQ_lotteryPushSwitch = false;

	/** 大乐透开奖推送开关状态 */
	private boolean state_DLT_lotteryPushSwitch = false;

	/** 足球胜负/任选9场 开奖推送开关状态 */
	private boolean state_RXJ_lotteryPushSwitch = false;

	/** 福彩3D开奖推送开关状态 */
	private boolean state_FC3D_lotteryPushSwitch = false;

	/** 双色球 购买提醒推送开关状态 */
	private boolean state_SSQ_timePushSwitch = false;

	/** 大乐透 购买提醒推送开关状态 */
	private boolean state_DLT_timePushSwitch = false;

	/** 足球胜负/任选9场 购买提醒推送开关状态 */
	private boolean state_RXJ_timePushSwitch = false;

	/** 福彩3D 购买提醒推送开关状态 */
	private boolean state_FC3D_timePushSwitch = false;

	/** 判断推送状态是否有改变 */
	private boolean isLotteryPushStateChanged = false;

	/** 提示用户保存状态对话框 */
	private Dialog saveTipDialog;

	private ProgressDialog progressDialog;

	private ValuesManager valuesManager;

	private Handler handler;

	private SendPushInfoCommunicater sendPushInfoCommunicater;

	/** 开奖提醒信息上传成功 */
	private final int SEND_LOTTERY_PUSH_INFO_SUCCEED = 10001;
	/** 开奖提醒信息上传失败 */
	private final int SEND_LOTTERY_PUSH_INFO_FAILED = 10002;

	private Calendar calendar;

	/********************* 滚轮 --end *************************/
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.option_push_act);
		initData();
		initViews();
		initHandler();

		calendar = Calendar.getInstance();
	}

	private void initHandler() {
		handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);

				progressDialog.dismiss();

				switch (msg.what) {

				case SEND_LOTTERY_PUSH_INFO_SUCCEED:

					valuesManager.saveLotteryPushState();
					isLotteryPushStateChanged = false;
					Toast.makeText(PushAct.this, "设置保存成功", Toast.LENGTH_SHORT).show();
					PushAct.this.finish();

					break;

				case SEND_LOTTERY_PUSH_INFO_FAILED:

					Toast.makeText(PushAct.this, sendPushInfoCommunicater.getServerMsg(), Toast.LENGTH_SHORT).show();

					break;

				case Config.CONNECTION_FAIL:

					Toast.makeText(PushAct.this, "设置保存失败", Toast.LENGTH_SHORT).show();

					break;

				default:

					break;

				}
			}
		};
	}

	/**
	 * @Title: initData
	 * @Description: 初始化数据 小时为0~23 分钟为0~59
	 */
	private void initData() {

		// 获取保存的各个开关状态
		valuesManager = ValuesManager.getInstance(this);
		valuesManager.readValue();
		setInitialValue();

	}

	private void initViews() {

		progressDialog = new ProgressDialog(this);

		tvSetTime = (TextView) findViewById(R.id.option_push_act_tv_notify_time);
		tvSetTime.setText(remindTime_hours + Config.ONESPACE + Config.MAOHAO + Config.ONESPACE + remindTime_mins);

		linearAllPushContent = (LinearLayout) findViewById(R.id.option_push_act_linear_allContent);
		linearTimePushContent = (LinearLayout) findViewById(R.id.option_push_act_linear_timePushContent);

		linearSetTime = (LinearLayout) findViewById(R.id.option_push_act_linear_setTime);
		linearSetTime.setOnClickListener(this);

		cbxMasterPushSwitch = (CheckBox) findViewById(R.id.option_push_act_cbx_master_switch);
		cbxMasterPushSwitch.setChecked(state_masterPushSwitch);
		cbxMasterPushSwitch.setOnCheckedChangeListener(this);

		if (state_masterPushSwitch) {
			linearAllPushContent.setVisibility(View.VISIBLE);
		} else {
			linearAllPushContent.setVisibility(View.GONE);
		}

		cbxTimePushSiwtch = (CheckBox) findViewById(R.id.option_push_act_cbx_buyNotify_switch);
		cbxTimePushSiwtch.setChecked(state_timePushSwitch);
		cbxTimePushSiwtch.setOnCheckedChangeListener(this);

		if (state_timePushSwitch) {
			linearTimePushContent.setVisibility(View.VISIBLE);
		} else {
			linearTimePushContent.setVisibility(View.GONE);
		}

		cbxLotteryPushSwitch_SSQ = (CheckBox) findViewById(R.id.option_push_act_cbx_SSQ_lottery_switch);
		cbxLotteryPushSwitch_SSQ.setChecked(state_SSQ_lotteryPushSwitch);
		cbxLotteryPushSwitch_SSQ.setOnCheckedChangeListener(this);

		cbxLotteryPushSwitch_DLT = (CheckBox) findViewById(R.id.option_push_act_cbx_DLT_lottery_switch);
		cbxLotteryPushSwitch_DLT.setChecked(state_DLT_lotteryPushSwitch);
		cbxLotteryPushSwitch_DLT.setOnCheckedChangeListener(this);

		cbxLotteryPushSwitch_RXJ = (CheckBox) findViewById(R.id.option_push_act_cbx_RXJ_lottery_switch);
		cbxLotteryPushSwitch_RXJ.setChecked(state_RXJ_lotteryPushSwitch);
		cbxLotteryPushSwitch_RXJ.setOnCheckedChangeListener(this);

		cbxLotteryPushSwitch_FC3D = (CheckBox) findViewById(R.id.option_push_act_cbx_FC3D_lottery_switch);
		cbxLotteryPushSwitch_FC3D.setChecked(state_FC3D_lotteryPushSwitch);
		cbxLotteryPushSwitch_FC3D.setOnCheckedChangeListener(this);

		cbxTimePushSwitch_SSQ = (CheckBox) findViewById(R.id.option_push_act_cbx_SSQ_time_switch);
		cbxTimePushSwitch_SSQ.setChecked(state_SSQ_timePushSwitch);
		cbxTimePushSwitch_SSQ.setOnCheckedChangeListener(this);

		cbxTimePushSwitch_DLT = (CheckBox) findViewById(R.id.option_push_act_cbx_DLT_time_switch);
		cbxTimePushSwitch_DLT.setChecked(state_DLT_timePushSwitch);
		cbxTimePushSwitch_DLT.setOnCheckedChangeListener(this);

		cbxTimePushSwitch_RXJ = (CheckBox) findViewById(R.id.option_push_act_cbx_RXJ_time_switch);
		cbxTimePushSwitch_RXJ.setChecked(state_RXJ_timePushSwitch);
		cbxTimePushSwitch_RXJ.setOnCheckedChangeListener(this);

		cbxTimePushSwitch_FC3D = (CheckBox) findViewById(R.id.option_push_act_cbx_FC3D_time_switch);
		cbxTimePushSwitch_FC3D.setChecked(state_FC3D_timePushSwitch);
		cbxTimePushSwitch_FC3D.setOnCheckedChangeListener(this);

		btnBack = (ImageButton) findViewById(R.id.option_push_act_btn_back);
		btnBack.setOnClickListener(this);

		btnSave = (Button) findViewById(R.id.option_push_act_btn_save);
		btnSave.setOnClickListener(this);

	}

	// 捕获back键
	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		switch (event.getKeyCode()) {
		case KeyEvent.KEYCODE_BACK:

			// 判断用户是否做过修改，是否提示用户保存
			if (isLotteryPushStateChanged) {
				showTipDialog();
			}

			break;

		default:
			break;
		}
		return super.dispatchKeyEvent(event);
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	/*
	 * 获得之前保存的值
	 */
	private void setInitialValue() {

		state_masterPushSwitch = valuesManager.isState_masterPushSwitch();

		state_SSQ_lotteryPushSwitch = valuesManager.isState_SSQ_lotteryPushSwitch();

		state_DLT_lotteryPushSwitch = valuesManager.isState_DLT_lotteryPushSwitch();

		state_FC3D_lotteryPushSwitch = valuesManager.isState_FC3D_lotteryPushSwitch();

		state_RXJ_lotteryPushSwitch = valuesManager.isState_RXJ_lotteryPushSwitch();

		state_timePushSwitch = valuesManager.isState_timePushSwitch();

		state_SSQ_timePushSwitch = valuesManager.isState_SSQ_timePushSwitch();

		state_DLT_timePushSwitch = valuesManager.isState_DLT_timePushSwitch();

		state_FC3D_timePushSwitch = valuesManager.isState_FC3D_timePushSwitch();

		state_RXJ_timePushSwitch = valuesManager.isState_RXJ_timePushSwitch();

		remindTime_hours = valuesManager.getRemindTime_hours();

		remindTime_mins = valuesManager.getRemindTime_mins();

	}

	private CustomTimePicker timePicker;

	/**
	 * @Title: showDateDialog
	 * @Description: 显示设置时间的Dialog
	 */
	private void showDateDialog() {
		calendar.setTimeInMillis(System.currentTimeMillis());
		int mHour = calendar.get(Calendar.HOUR_OF_DAY);
		int mMinute = calendar.get(Calendar.MINUTE);

		if (timePicker == null) {

			OnTimeSetListener listener = new OnTimeSetListener() {

				@Override
				public void onTimeSet(TimePicker view, int hours, int min) {

					// 获取选中的时间
					if (hours < 10) {
						remindTime_hours = Config.NUM0 + String.valueOf(hours);
					} else {
						remindTime_hours = String.valueOf(hours);
					}
					if (min < 10) {
						remindTime_mins = Config.NUM0 + String.valueOf(min);
					} else {
						remindTime_mins = String.valueOf(min);
					}

					// 显示选中的时间
					tvSetTime.setText(remindTime_hours + Config.ONESPACE + Config.MAOHAO + Config.ONESPACE + remindTime_mins);

					// 以选中时间设置闹铃
					setNewAlarm(hours, min);
					// 保存购彩提醒时间
					valuesManager.setRemindTime_hours(remindTime_hours);
					valuesManager.setRemindTime_mins(remindTime_mins);
					valuesManager.saveTimePushNum();

				}
			};

			timePicker = new CustomTimePicker(PushAct.this, listener, mHour, mMinute, true);
		}
		timePicker.show();

	}

	private class CustomTimePicker extends TimePickerDialog {

		public CustomTimePicker(Context context, OnTimeSetListener listener, int hours, int min, boolean is24Style) {
			super(context, listener, hours, min, is24Style);
			setButton("确定", this);
		}

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		// 点击显示设置时间滚轮
		case R.id.option_push_act_linear_setTime:

			showDateDialog();

			break;

		// 返回
		case R.id.option_push_act_btn_back:

			// 判断用户是否做过修改，是否提示用户保存
			if (isLotteryPushStateChanged) {
				showTipDialog();
			} else {
				this.finish();
			}

			break;

		// 保存
		case R.id.option_push_act_btn_save:

			progressDialog.show();
			saveLotteryPushState();

			break;

		// 取消保存
		case R.id.dialogquit_btn_cancel:

			saveTipDialog.dismiss();
			this.finish();

			break;

		// 确定保存
		case R.id.dialogquit_btn_submit:

			progressDialog.show();
			saveTipDialog.dismiss();
			saveLotteryPushState();

			break;

		default:
			break;
		}
	}

	/**
	 * @Title: setNewAlarm
	 * @Description: 设置一个新的购彩提醒
	 * @param: @param hours 小时
	 * @param: @param min 分钟
	 */
	private void setNewAlarm(int hours, int min) {

		// 得到使用AlarmManager的权限
		AlarmManager alarms = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

		// 达到条件后会触发的工作
		Intent intent = new Intent(this, NotificationReceiver.class);
		intent.setAction(Config.ALARMACTION);
		PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);

		// 时间转换
		Calendar ca = Calendar.getInstance();
		ca.set(ca.get(Calendar.YEAR), ca.get(Calendar.MONTH), ca.get(Calendar.DAY_OF_MONTH), hours, min, 0);
		long alarmPushTime = ca.getTimeInMillis();

		// 如果已设定时间为过去时间，则将时间定为明日的这个时间
		if (alarmPushTime < System.currentTimeMillis()) {
			ca.set(ca.get(Calendar.YEAR), ca.get(Calendar.MONTH), ca.get(Calendar.DAY_OF_MONTH) + 1, hours, min, 0);
			alarmPushTime = ca.getTimeInMillis();
		}
		// 设定时间
		alarms.set(AlarmManager.RTC_WAKEUP, alarmPushTime, pendingIntent);

	}

	@Override
	protected void onPause() {
		super.onPause();

	}

	/**
	 * @Title: showTipDialog
	 * @Description: 提示用户是否保存推送状态
	 */
	private void showTipDialog() {

		if (saveTipDialog == null) {

			saveTipDialog = new Dialog(this, R.style.dialog);
			saveTipDialog.getWindow().setContentView(R.layout.dialog_quit);

			TextView tvTitleMsg = (TextView) saveTipDialog.getWindow().findViewById(R.id.dialogquit_tv_title);
			tvTitleMsg.setText("推送状态保存");
			TextView tvDialogMsg = (TextView) saveTipDialog.getWindow().findViewById(R.id.dialogquit_tv_msg);
			tvDialogMsg.setText("推送状态已修改，是否保存？");
			Button btnDialogcancel = (Button) saveTipDialog.getWindow().findViewById(R.id.dialogquit_btn_cancel);
			btnDialogcancel.setOnClickListener(this);
			Button btnDialogSubmit = (Button) saveTipDialog.getWindow().findViewById(R.id.dialogquit_btn_submit);
			btnDialogSubmit.setOnClickListener(this);
		}

		saveTipDialog.show();
	}

	/**
	 * 组织开奖推送状态数据并上传保存到服务器
	 */
	private void saveLotteryPushState() {

		// 数据组织
		String isMasterState;
		if (state_masterPushSwitch) {
			isMasterState = Config.NUM1;
		} else {
			isMasterState = Config.NUM0;
		}

		String lotidList = Config.SHUANGSEQIU + Config.COMMA + Config.DALETOU + Config.COMMA + Config.RENXUANJIU + Config.COMMA + Config.FUCAI3D;

		StringBuilder sb = new StringBuilder();
		if (state_SSQ_lotteryPushSwitch) {
			sb.append(Config.NUM1);
		} else {
			sb.append(Config.NUM0);
		}
		sb.append(Config.COMMA);

		if (state_DLT_lotteryPushSwitch) {
			sb.append(Config.NUM1);
		} else {
			sb.append(Config.NUM0);
		}
		sb.append(Config.COMMA);

		if (state_RXJ_lotteryPushSwitch) {
			sb.append(Config.NUM1);
		} else {
			sb.append(Config.NUM0);
		}
		sb.append(Config.COMMA);

		if (state_FC3D_lotteryPushSwitch) {
			sb.append(Config.NUM1);
		} else {
			sb.append(Config.NUM0);
		}

		String pushStateList = sb.toString();
		// 通信
		sendStateThread(isMasterState, lotidList, pushStateList);
	}

	/**
	 * @Title: saveBuyAlarmState
	 * @Description: 保存购买提醒开关状态
	 */
	private void saveBuyAlarmState() {

		// 总开关状态本地保存
		valuesManager.saveMasterSwitchState();
		// 购彩提醒开关状态本地保存
		valuesManager.saveTimePushState();
		// 购彩提醒开关时间保存
		valuesManager.saveTimePushNum();

	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

		switch (buttonView.getId()) {
		// 推送总开关状态变化
		case R.id.option_push_act_cbx_master_switch:

			EDebug.o(this, "总开关状态变化为 " + isChecked);

			isLotteryPushStateChanged = true;

			state_masterPushSwitch = isChecked;

			if (isChecked) {
				linearAllPushContent.setVisibility(View.VISIBLE);
			} else {
				linearAllPushContent.setVisibility(View.GONE);
			}

			valuesManager.setState_masterPushSwitch(isChecked);

			break;
		// 时间推送总开关状态变化
		case R.id.option_push_act_cbx_buyNotify_switch:

			EDebug.o(this, "时间推送开关状态变化为 " + isChecked);

			state_timePushSwitch = isChecked;

			if (isChecked) {
				linearTimePushContent.setVisibility(View.VISIBLE);
			} else {
				linearTimePushContent.setVisibility(View.GONE);
			}

			valuesManager.setState_timePushSwitch(isChecked);

			saveBuyAlarmState();

			break;
		// 双色球开奖信息推送开关状态变化
		case R.id.option_push_act_cbx_SSQ_lottery_switch:

			EDebug.o(this, "双色球开奖信息推送开关状态变化为 " + isChecked);

			isLotteryPushStateChanged = true;

			state_SSQ_lotteryPushSwitch = isChecked;

			valuesManager.setState_SSQ_lotteryPushSwitch(isChecked);

			break;
		// 大乐透开奖信息推送开关状态变化
		case R.id.option_push_act_cbx_DLT_lottery_switch:

			EDebug.o(this, "大乐透开奖信息推送开关状态变化为 " + isChecked);

			isLotteryPushStateChanged = true;

			state_DLT_lotteryPushSwitch = isChecked;

			valuesManager.setState_DLT_lotteryPushSwitch(isChecked);

			break;
		// 任选九开奖信息推送开关状态变化
		case R.id.option_push_act_cbx_RXJ_lottery_switch:

			EDebug.o(this, "任选九开奖信息推送开关状态变化为 " + isChecked);

			isLotteryPushStateChanged = true;

			state_RXJ_lotteryPushSwitch = isChecked;

			valuesManager.setState_RXJ_lotteryPushSwitch(isChecked);

			break;
		// 福彩3D开奖信息推送开关状态变化
		case R.id.option_push_act_cbx_FC3D_lottery_switch:

			EDebug.o(this, "福彩3D开奖信息推送开关状态变化为 " + isChecked);

			isLotteryPushStateChanged = true;

			state_FC3D_lotteryPushSwitch = isChecked;

			valuesManager.setState_FC3D_lotteryPushSwitch(isChecked);

			break;
		// 双色球购彩推送开关状态变化
		case R.id.option_push_act_cbx_SSQ_time_switch:

			EDebug.o(this, "双色球购彩推送开关状态变化为 " + isChecked);

			state_SSQ_timePushSwitch = isChecked;

			valuesManager.setState_SSQ_timePushSwitch(isChecked);

			saveBuyAlarmState();

			break;
		// 大乐透购彩推送开关状态变化
		case R.id.option_push_act_cbx_DLT_time_switch:

			EDebug.o(this, "大乐透购彩推送开关状态变化为 " + isChecked);

			state_DLT_timePushSwitch = isChecked;

			valuesManager.setState_DLT_timePushSwitch(isChecked);

			saveBuyAlarmState();

			break;
		// 任选九购彩推送开关状态变化
		case R.id.option_push_act_cbx_RXJ_time_switch:

			EDebug.o(this, "任选九购彩推送开关状态变化为 " + isChecked);

			state_RXJ_timePushSwitch = isChecked;

			valuesManager.setState_RXJ_timePushSwitch(isChecked);

			saveBuyAlarmState();

			break;
		// 福彩3D购彩推送开关状态变化
		case R.id.option_push_act_cbx_FC3D_time_switch:

			EDebug.o(this, "福彩3D购彩推送开关状态变化为 " + isChecked);

			state_FC3D_timePushSwitch = isChecked;

			valuesManager.setState_FC3D_timePushSwitch(isChecked);

			saveBuyAlarmState();

			break;

		}

	}

	/** 发送开奖提醒状态给服务的通信线程 */
	private void sendStateThread(final String masterState, final String lotidList, final String pushStateList) {
		new Thread() {
			@Override
			public void run() {
				super.run();

				if (sendPushInfoCommunicater == null) {
					sendPushInfoCommunicater = new SendPushInfoCommunicater();
				}
				try {

					SharedPreferences sharePre = getSharedPreferences(Config.CLIENT_PREFERENCES, Context.MODE_PRIVATE);
					// 获取唯一设备号，没有就默认“0000”
					String userIMEI = sharePre.getString(Constants.DEVICE_ID, Config.DEFAULT_LEAGUAGE_NUM);

					boolean isSucceed = sendPushInfoCommunicater.isSendSucceed(userIMEI, masterState, lotidList, pushStateList);

					if (isSucceed) {
						Message msg = handler.obtainMessage(SEND_LOTTERY_PUSH_INFO_SUCCEED);
						handler.sendMessage(msg);
					} else {
						Message msg = handler.obtainMessage(SEND_LOTTERY_PUSH_INFO_FAILED);
						handler.sendMessage(msg);
					}
				} catch (Exception e) {
					Message msg = handler.obtainMessage(Config.CONNECTION_FAIL);
					handler.sendMessage(msg);
				}
			}
		}.start();
	}

}
